//
//  MWNetworkManager.m
//  WuLianWang-iOS
//
//  Created by liuyiming on 2019/9/10.
//  Copyright © 2019 www.oakev.cn. All rights reserved.
//

#import "MWNetworkManager.h"
@implementation MWNetworkManager

+ (instancetype)manager {
    static MWNetworkManager *manager = nil;
    static dispatch_once_t onceToken ;
    dispatch_once(&onceToken, ^{
        manager = [[super allocWithZone:NULL] init] ;
    }) ;
    return manager;
}


/**
 *  发送get请求
 */
- (NSURLSessionDataTask *)GET:(NSString *)url
                   parameters:(id __nullable)parameters
          httpHeaderKeyValues:(NSDictionary *)header
                     progress:(void (^)(NSProgress *downloadProgress))downloadProgressBlock
                      success:(void (^)(id responseObject))success
                      failure:(void (^)(NSError *error))failure {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // 可以接受的类型
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/html", @"text/javascript", @"text/plain", nil];
    // 请求超时的时间
    manager.requestSerializer.timeoutInterval = 30;
    // Header 请求头
    if (header) {
        [header enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
            [manager.requestSerializer setValue:obj forHTTPHeaderField:key];
        }];
    }
    
    NSURLSessionDataTask *task = [manager GET:url parameters:parameters progress:downloadProgressBlock success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
            hud.label.text = [[MWConfigManager manager] objectForKey:@"network_error" defaultValue:@"网络异常，请稍后再试..."];
            hud.mode = MBProgressHUDModeText;
            [hud hideAnimated:YES afterDelay:2];
            failure(error);
            
        }
    }];
    
    return task;
}

- (NSURLSessionDataTask *)GET:(NSString *)url
                   parameters:(id __nullable)parameters
                     progress:(void (^)(NSProgress *downloadProgress))downloadProgressBlock
                      success:(void (^)(id responseObject))success
                      failure:(void (^)(NSError *error))failure {
    return [self GET:url parameters:parameters httpHeaderKeyValues:@{} progress:downloadProgressBlock success:success failure:failure];
}




/**
 *  发送post请求
 */
- (NSURLSessionDataTask *)POST:(NSString *)url
                    parameters:(id)parameters
           httpHeaderKeyValues:(NSDictionary *)header
                      progress:(void (^)(NSProgress *downloadProgress))downloadProgressBlock
                       success:(void (^)(id responseObject))success
                       failure:(void (^)(NSError *error))failure {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // 可以接受的类型
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/html", @"text/javascript", @"text/plain", nil];
    // 请求超时的时间
    manager.requestSerializer.timeoutInterval = 30;
    // Header 请求头
    if (header) {
        [header enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
            [manager.requestSerializer setValue:obj forHTTPHeaderField:key];
        }];
    }
    
    DLog(@"======== 请求URL ======== \n %@", url);
    DLog(@"======== 请求参数 ======== \n %@", parameters);
    
    NSURLSessionDataTask *task = [manager POST:url parameters:parameters progress:downloadProgressBlock success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            NSString *jsonStr = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
            NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
            NSError *error;
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&error];
            
            DLog(@"======== 请求结果 ======== \n %@", jsonStr);
            success(dic);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
//            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
//            hud.label.text = [[MWConfigManager manager] objectForKey:@"network_error" defaultValue:@"网络异常，请稍后再试..."];
//            hud.mode = MBProgressHUDModeText;
//            [hud hideAnimated:YES afterDelay:2];
            failure(error);
        }
    }];
    
    return task;
}

- (NSURLSessionDataTask *)POST:(NSString *)url
                    parameters:(id)parameters
                      progress:(void (^)(NSProgress *downloadProgress))downloadProgressBlock
                       success:(void (^)(id responseObject))success
                       failure:(void (^)(NSError *error))failure {
    return [self POST:url parameters:parameters httpHeaderKeyValues:@{} progress:downloadProgressBlock success:success failure:failure];
}

- (void)uploadFile:(NSString *)url parameters:(id)parameters {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // 可以接受的类型
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/html", @"text/javascript", @"text/plain", nil];
    
    NSURLSessionDataTask *task = [manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        UIImage *image = [UIImage imageNamed:@"bg_banner_placeholder"];
        NSData *data = UIImagePNGRepresentation(image);
        
        if (data == nil) {
            return ;
        }
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
        
        [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/jpg/png/jpeg"];
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
       
        NSString *jsonStr = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
//        NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
//        NSError *error;
//        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&error];
        
        DLog(@"======== 请求结果 ======== \n %@", jsonStr);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         DLog(@"======== 请求结果 ======== \n %@", error);
    }];
}

/**
 *  上传文件
 */
- (NSURLSessionDataTask *)upload:(NSString *)url
                      parameters:(id)parameters
                         UIImage:image
                         success:(void (^)(id responseObject))success
                         failure:(void (^)(NSError *error))failure {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // 可以接受的类型
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/html", @"text/javascript", @"text/plain", nil];

    // 请求超时的时间
    manager.requestSerializer.timeoutInterval = 30;
    
    NSURLSessionDataTask *task = [manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *data = UIImageJPEGRepresentation(image, 0.5);

        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
        
        [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/jpg/png/jpeg"];
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            
            NSString *jsonStr = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
            NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
            NSError *error;
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&error];
                       
            DLog(@"======== 请求结果 ======== \n %@", jsonStr);
            
            success(dic);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
            hud.label.text = [[MWConfigManager manager] objectForKey:@"network_error" defaultValue:@"网络异常，请稍后再试..."];
            hud.mode = MBProgressHUDModeText;
            [hud hideAnimated:YES afterDelay:2];
            failure(error);
        }
    }];
    
    return task;
}

/**
 *  下载
 */
- (NSURLSessionDownloadTask *)download:(NSString *)url
                            parameters:(id)parameters
                   httpHeaderKeyValues:(NSDictionary *)header
                              progress:(void (^)(NSProgress *downloadProgress))downloadProgressBlock
                           destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
                     completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler {
    
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:downloadProgressBlock destination:destination completionHandler:completionHandler];
    [task resume];
    return task;
}

- (NSURLSessionDownloadTask *)download:(NSString *)url
                            parameters:(id)parameters
                              progress:(void (^)(NSProgress *downloadProgress))downloadProgressBlock
                           destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
                     completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler {
    return [self download:url parameters:parameters httpHeaderKeyValues:@{} progress:downloadProgressBlock destination:destination completionHandler:completionHandler];
}

@end
